package com.weds.data_sync.db;


import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.PostgreSqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.querys.PostgreSqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.keywords.PostgreSqlKeyWordsHandler;

import java.util.Collections;

/**
 * 普通代码生成
 */
public class MyBatisPlusGenerator {


    public static void main(String[] args) {
        MyBatisPlusGenerator config = new MyBatisPlusGenerator();
        AutoGenerator generator = new AutoGenerator(config.getDataSourceConfig());
        generator.global(config.getGlobalConfig())
                .packageInfo(config.getPackageConfig())
                .template(config.getTemplateConfig())
                .injection(config.getInjectionConfig())
                .strategy(config.getStrategyConfig());
        // 切换成 FreeMarker模板
        generator.execute(new FreemarkerTemplateEngine());

    }

    /**
     * 数据源配置
     * @return
     */
    public DataSourceConfig getDataSourceConfig() {
        DataSourceConfig dbConfig = new DataSourceConfig
                // TODO TODO TODO TODO TODO TODO  数据库配置
                .Builder("jdbc:postgresql://192.168.116.128:5432/postgres", "postgres", "123456")
                .dbQuery(new PostgreSqlQuery())
                .schema("public")
                .typeConvert(new PostgreSqlTypeConvert())
                .keyWordsHandler(new PostgreSqlKeyWordsHandler())
                .build();

        return dbConfig;
    }

    /**
     * 全局配置
     * @return
     */
    public GlobalConfig getGlobalConfig() {
        GlobalConfig globalConfig = new GlobalConfig.Builder()
                .outputDir("C:\\Users\\admin\\Desktop\\tmp")
                .author("lhw")
                //.enableKotlin()
                .enableSwagger()
                .dateType(DateType.TIME_PACK)
                .commentDate("yyyy-MM-dd")
                .build();

        return globalConfig;
    }

    /**
     * 包配置
     * @return
     */
    public PackageConfig getPackageConfig() {
        PackageConfig packageConfig = new PackageConfig.Builder()
                .parent("com.weds.data_sync")
                .moduleName("")
                .entity("entity")
                .service("service")
                .serviceImpl("service.impl")
                .mapper("mapper")
                .xml("mapper.xml")
                .controller("controller")
                // TODO TODO TODO TODO TODO TODO  文件输出地址
                .pathInfo(Collections.singletonMap(OutputFile.xml, "C:\\Users\\admin\\Desktop\\tmp\\xml"))
                .build();
        return packageConfig;
    }

    /**
     * 模板配置
     * @return
     */
    public TemplateConfig getTemplateConfig() {
        TemplateConfig templateConfig = new TemplateConfig.Builder()
                .disable(TemplateType.ENTITY)
                .entity("/templates/entity.java")
                .service("/templates/service.java")
                .serviceImpl("/templates/serviceImpl.java")
                .mapper("/templates/mapper.java")
                .xml("/templates/mapper.xml")
                .controller("/templates/controller.java")
                .build();

        return templateConfig;
    }


    /**
     * 生成问价注入配置
     * @return
     */
    public InjectionConfig getInjectionConfig() {
        InjectionConfig injectionConfig = new InjectionConfig.Builder()
                .beforeOutputFile((tableInfo, objectMap) -> {
                    System.out.println("开始生成 tableInfo: " + tableInfo.getEntityName() + " objectMap: " + objectMap.size());
                })
                // 自定义map(注入到freemarker末班引擎中的变量)
                .customMap(Collections.singletonMap("springdoc", true))
                // 后置输出文件，需要自己手动创建 /templates/test.ftl
                //.customFile(Collections.singletonMap("test.txt", "/templates/test.ftl"))
                .build();
        return injectionConfig;
    }

    /**
     * 生成策略
     * @return
     */
    public StrategyConfig getStrategyConfig() {
        StrategyConfig strategyConfig = new StrategyConfig.Builder()
                .enableCapitalMode()
                .enableSkipView()
                .disableSqlFilter()
                .enableSchema()
                // likeTable 与 notLikeTable 只能配置一项
                // 模糊表匹配(sql 过滤)
                //.likeTable(new LikeTable("USER"))
                // include 与 exclude 只能配置一项
                // TODO TODO TODO TODO TODO   要生成的表，不填生成全部
                // 增加表匹配(内存过滤)
                .addInclude("data_sync_plan_record")
                // 增加过滤表前缀
                //.addTablePrefix("t_", "c_")
                // 增加过滤字段前缀
                //.addFieldSuffix("_flag")

                //.entityBuilder()
                //.controllerBuilder()
                //.mapperBuilder()
                //.serviceBuilder()
                .build();

        getEntityStrategyConfig(strategyConfig)
                .getControllerStrategyConfig(strategyConfig)
                .getServiceStrategyConfig(strategyConfig)
                .getMapperStrategyConfig(strategyConfig);

        return strategyConfig;
    }


    public MyBatisPlusGenerator getEntityStrategyConfig(StrategyConfig strategyConfig) {
        strategyConfig
                .entityBuilder()
                //.superClass(BaseEntity.class)
                .disableSerialVersionUID()
                .enableChainModel()
                .enableLombok()
                .enableRemoveIsPrefix()
                .enableTableFieldAnnotation()
                //.enableActiveRecord()
                //.versionColumnName("version")
                //.versionPropertyName("version")
                //.logicDeleteColumnName("deleted")
                //.logicDeletePropertyName("deleteFlag")
                .naming(NamingStrategy.underline_to_camel)
                .columnNaming(NamingStrategy.underline_to_camel)
                // 父类公共字段
                //.addSuperEntityColumns("id", "created_by", "created_time", "updated_by", "updated_time")
                //.addIgnoreColumns("age")
                //.addTableFills(new Column("create_time", FieldFill.INSERT))
                //.addTableFills(new Property("updateTime", FieldFill.INSERT_UPDATE))
                .idType(IdType.AUTO)
                .formatFileName("%sDO")
                .build();
        return this;
    }

    public MyBatisPlusGenerator getControllerStrategyConfig(StrategyConfig strategyConfig) {
        strategyConfig
                .controllerBuilder()
                //.superClass(BaseController.class)
                .enableFileOverride()
                .enableHyphenStyle()
                .enableRestStyle()
                .formatFileName("%sController")
                .build();
        return this;
    }

    public MyBatisPlusGenerator getServiceStrategyConfig(StrategyConfig strategyConfig) {
        strategyConfig
                .serviceBuilder()
                //.superServiceClass(BaseService.class)
                //.superServiceImplClass(BaseServiceImpl.class)
                .formatServiceFileName("%sService")
                .formatServiceImplFileName("%sServiceImp")
                .build();
        return this;
    }


    public MyBatisPlusGenerator getMapperStrategyConfig(StrategyConfig strategyConfig) {
        strategyConfig
                .mapperBuilder()
                .superClass(BaseMapper.class)
                .enableFileOverride()
                .enableBaseResultMap()
                .enableBaseColumnList()
                //.cache(MyMapperCache.class)
                .formatMapperFileName("%sMapper")
                .formatXmlFileName("%sMapper")
                .build();
        return this;
    }


}
